package com.bdqn.dao;

import java.sql.*;

public class BaseDao {
    static Connection connection;
    static PreparedStatement preparedStatement;
    static ResultSet set;
    //获取连接
    public static Connection getConnection() throws Exception {
        //加载驱动 8版本使用com.mysql.cj.jdbc.Driver
        Class.forName("com.mysql.cj.jdbc.Driver");
        //创建连接串
        String url="jdbc:mysql://localhost:3306/newproject?useUnicode=true&characterEncoding=UTF-8";
        connection=DriverManager.getConnection(url,"root","root");
        return connection;
    }
    //读取数据
    public static ResultSet getResultSet(String sql,Object[] objects) throws Exception {
        if(getConnection()!=null) {
            preparedStatement = connection.prepareStatement(sql);

            for (int i = 0; i < objects.length; i++) {
                preparedStatement.setObject(i + 1, objects[i]);
            }
            set = preparedStatement.executeQuery();
            return set;
        }
        return null;
    }
    //增，删，改
    //delete from ming where id in (?,?,?)
    public static int update(String sql,Object[] objects) throws Exception {
        if(getConnection()!=null) {
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < objects.length; i++) {
                preparedStatement.setObject(i + 1, objects[i]);
            }
            return preparedStatement.executeUpdate();
        }
        return 0;
    }
    //关闭资源
    public static  void close() throws SQLException {
        /*static Connection connection;
        static PreparedStatement preparedStatement;
        static ResultSet set;*/
        if(set!=null)
        {
            set.close();
        }
        if(preparedStatement!=null)
        {
            preparedStatement.close();
        }
        if(connection!=null)
        {
            connection.close();
        }
    }
}
